1. 题目描述(简单难度)

[success] 589. N 叉树的前序遍历

2. 解法一:DFS

class Solution {
    List<Integer> resp = new ArrayList<>();
    public List<Integer> preorder(Node root) {
        if(root == null){
            return resp;
        }
        dfs(root);
        return resp;
    }

    public void dfs(Node root){
        if(root == null){
            return;
        }
        resp.add(root.val);
        for(Node node : root.children){
            dfs(node);
        }
    }
}

3. 解法二:BFS

class Solution {
    List<Integer> resp = new ArrayList<>();
    public List<Integer> preorder(Node root) {
        if(root == null){
            return resp;
        }
        Deque<Node> deque = new LinkedList<>();
        deque.offer(root);
        while(!deque.isEmpty()){
          Node poll =  deque.pollLast();
          resp.add(poll.val);
          Collections.reverse(poll.children);
          for(Node node : poll.children){
              deque.offerLast(node);
          }
        }
        return resp;
    }
}
© gaohueric all right reserved,powered by Gitbook文件修订时间: 2021-12-08 23:22:22

results matching ""

    No results matching ""